/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities;

import beans.LoginBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;


/**
 *
 * @author Ahmet
 */
@FacesConverter(value="restConverter", forClass=Restaurant.class)
public class RestConverter implements Converter{

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        if (context == null) {
            throw new NullPointerException("context");
        }
        if (component == null) {
            throw new NullPointerException("component");
        }
//        String temp[] = new String[4];
//        StringTokenizer tokenizer = new StringTokenizer(value, "$$");
//        int i = 0;
//        while (tokenizer.hasMoreTokens()) {
//            temp[i] = tokenizer.nextToken();
//            i++;
//        }
//        if (temp[3] == null)
//            temp[3] = "";
//        System.out.println(temp[0] + " " + temp[1] + " " + temp[2] + " " + temp[3]);
//        int rid = Integer.parseInt(temp[0]);
//        Restaurant rest = new Restaurant(rid,temp[1],temp[2],temp[3]);
        Integer rid;
        try {
            rid = new Integer(value); 
        } catch (NumberFormatException ne) {
            throw new NumberFormatException("RestID not valid Integer!");
        }
        System.out.println("##################RESTAURANT ID = " + rid);
        Restaurant rest;
        LoginBean loginBean = (LoginBean) context.getExternalContext().getSessionMap().get("loginBean");
        System.out.println("EMMMMMM = " + loginBean.getEm().toString());
        rest = (Restaurant) loginBean.getEm().createNamedQuery("Restaurant.findByRid").setParameter("rid", rid).getSingleResult();
            //Restaurant rest = (Restaurant) em.createNamedQuery("Restaurant.findByName").setParameter("name", rid).getSingleResult();
        
        System.out.println("Restoran = " + rest.getName() + " Location = " + rest.getLocation());
        return rest;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (context == null) {
            throw new NullPointerException("context");
        }
        if (component == null) {
            throw new NullPointerException("component");
        }
        final Restaurant restaurant = (Restaurant) value;
        return restaurant.getRid().toString();

    }
    
}
